/* global React */
// Standings — championship table with live "drop worst N" + minimum-starts rules,
// so drivers who miss 1–3 races aren't sunk. Change the controls to trial any rule.
function StandingsScreen() {
  const { StatTile, Card, Badge, Avatar, PositionBadge } = window.GT7LeagueDesignSystem_258437;
  const D = window.GT7DATA;
  const R = D.titleRules;
  const PLAYED = R.completedRounds;

  const [dropN, setDropN] = React.useState(R.dropWorst);
  const [minStarts, setMinStarts] = React.useState(R.minStarts);

  const computed = D.drivers.map(d => {
    const slots = d.rounds.map(x => (x == null ? 0 : x));   // missed = 0
    const starts = d.rounds.filter(x => x != null).length;
    const raw = slots.reduce((a, x) => a + x, 0);
    const keepCount = Math.max(1, slots.length - dropN);
    const kept = [...slots].sort((a, b) => b - a).slice(0, keepCount);
    const adjusted = kept.reduce((a, x) => a + x, 0);
    return { ...d, slots, starts, raw, adjusted, dropped: raw - adjusted, eligible: starts >= minStarts };
  });
  const ranked = [...computed].sort((a, b) => (Number(b.eligible) - Number(a.eligible)) || (b.adjusted - a.adjusted));
  const leader = ranked.find(d => d.eligible) || ranked[0];
  const mostPoles = [...computed].sort((a, b) => b.poles - a.poles)[0];
  const mostFL = [...computed].sort((a, b) => b.fl - a.fl)[0];
  const eligibleCount = computed.filter(d => d.eligible).length;

  let rank = 0;
  const cols = '38px 42px 1fr 62px 64px 66px 92px 104px';

  return (
    <div>
      <PageTitle eyebrow={D.season} title="Championship Standings" />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 20 }}>
        <StatTile label="Leader" value={leader.name.split(' ')[0]} accent="gold" sublabel={`${leader.adjusted} pts (counting)`} />
        <StatTile label="Most poles" value={mostPoles.poles} accent="cyan" sublabel={mostPoles.name} />
        <StatTile label="Most fastest laps" value={mostFL.fl} accent="var(--fastest-lap)" sublabel={mostFL.name} />
        <StatTile label="Title-eligible" value={`${eligibleCount}/${D.drivers.length}`} accent="green" sublabel={`${minStarts}+ starts`} />
      </div>

      {/* Rule controls */}
      <Card style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 28, alignItems: 'center' }}>
          <div>
            <FieldLabel>Drop worst rounds</FieldLabel>
            <Segmented options={['0', '1', '2', '3']} value={String(dropN)} onChange={v => setDropN(Number(v))} />
          </div>
          <div>
            <FieldLabel>Min starts to be eligible</FieldLabel>
            <Stepper value={minStarts} set={setMinStarts} lo={0} hi={PLAYED} />
          </div>
          <div style={{ flex: 1, minWidth: 220, alignSelf: 'flex-end' }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 14px',
              background: 'rgba(23,198,232,0.08)', border: '1px solid rgba(23,198,232,0.3)', borderRadius: 'var(--radius-sm)',
            }}>
              <Badge tone="pole">Rule</Badge>
              <span style={{ fontSize: 13.5, color: 'var(--text-body)' }}>
                Best <strong style={{ color: 'var(--text-strong)' }}>{Math.max(1, PLAYED - dropN)} of {PLAYED}</strong> rounds count · must start <strong style={{ color: 'var(--text-strong)' }}>{minStarts}+</strong> to win the title
              </span>
            </div>
          </div>
        </div>
      </Card>

      {/* Table */}
      <Card padded={false}>
        <div style={{
          display: 'grid', gridTemplateColumns: cols, gap: 12, padding: '11px 16px',
          borderBottom: '1px solid var(--border-strong)', alignItems: 'center',
          fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--text-faint)',
        }}>
          <span>Pos</span><span>No</span><span>Driver</span><span>Starts</span><span>Raw</span><span>Dropped</span><span style={{ textAlign: 'right' }}>Counting</span><span style={{ textAlign: 'right' }}>Status</span>
        </div>

        {ranked.map(d => {
          const pos = d.eligible ? ++rank : null;
          const isLeader = d.eligible && pos === 1;
          return (
            <div key={d.number} style={{
              display: 'grid', gridTemplateColumns: cols, gap: 12, padding: '10px 16px', alignItems: 'center',
              borderBottom: '1px solid var(--divider)',
              borderLeft: `2px solid ${isLeader ? 'var(--gold-500)' : 'transparent'}`,
              background: isLeader ? 'rgba(245,197,66,0.05)' : d.eligible ? 'transparent' : 'rgba(255,176,32,0.03)',
              opacity: d.eligible ? 1 : 0.72,
            }}>
              <span>{pos ? <PositionBadge position={pos} size={26} /> : <span style={{ color: 'var(--text-faint)', fontFamily: 'var(--font-mono)', paddingLeft: 8 }}>—</span>}</span>
              <Avatar number={d.number} name={d.name} size={30} color={isLeader ? 'var(--gold-500)' : 'var(--border-strong)'} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
                <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text-strong)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</span>
                <div style={{ display: 'flex', gap: 5 }}>
                  {d.poles > 0 && <Badge tone="pole">{d.poles} pole{d.poles > 1 ? 's' : ''}</Badge>}
                  {d.fl > 0 && <Badge tone="fastest">{d.fl} FL</Badge>}
                </div>
              </div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: d.starts >= minStarts ? 'var(--text-muted)' : 'var(--amber-400)' }}>{d.starts}/{PLAYED}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-faint)' }}>{d.raw}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: d.dropped > 0 ? 'var(--red-300)' : 'var(--text-faint)' }}>{d.dropped > 0 ? `-${d.dropped}` : '—'}</span>
              <span style={{ textAlign: 'right', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 21, color: isLeader ? 'var(--gold-400)' : 'var(--text-strong)', fontVariantNumeric: 'tabular-nums' }}>{d.adjusted}</span>
              <span style={{ textAlign: 'right' }}>{d.eligible ? <Badge tone="positive">Eligible</Badge> : <Badge tone="caution">{minStarts - d.starts} more start{minStarts - d.starts > 1 ? 's' : ''}</Badge>}</span>
            </div>
          );
        })}
      </Card>

      <div style={{ marginTop: 16, fontSize: 12.5, color: 'var(--text-faint)', lineHeight: 1.7 }}>
        <strong style={{ color: 'var(--text-muted)' }}>How it works:</strong> a missed race scores 0; “drop worst” removes each driver’s lowest {dropN || 'N'} round{dropN === 1 ? '' : 's'} (which absorbs an absence). Drivers below the start minimum still race and score, but aren’t eligible for the championship.<br />
        <strong style={{ color: 'var(--text-muted)' }}>Tie-breakers:</strong> most feature wins → most total wins → most poles → most fastest laps → best finish in the season finale.
      </div>
    </div>
  );
}

function FieldLabel({ children }) {
  return <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 600, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>{children}</div>;
}
function Segmented({ options, value, onChange }) {
  return (
    <div style={{ display: 'inline-flex', background: 'var(--ink-900)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', padding: 3, gap: 3 }}>
      {options.map(o => {
        const on = o === value;
        return (
          <button key={o} onClick={() => onChange(o)} style={{
            minWidth: 40, padding: '7px 14px', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-xs)',
            fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500,
            background: on ? 'var(--brand)' : 'transparent', color: on ? '#fff' : 'var(--text-faint)', transition: 'background 120ms',
          }}>{o}</button>
        );
      })}
    </div>
  );
}
function Stepper({ value, set, lo, hi }) {
  const btn = (label, onClick) => <button onClick={onClick} style={{ width: 32, height: 36, border: 'none', background: 'var(--surface-raised)', color: 'var(--text-strong)', fontSize: 16, cursor: 'pointer', fontFamily: 'var(--font-mono)' }}>{label}</button>;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-sm)', overflow: 'hidden' }}>
      {btn('–', () => set(Math.max(lo, value - 1)))}
      <span style={{ minWidth: 44, textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 15, color: 'var(--text-strong)' }}>{value}</span>
      {btn('+', () => set(Math.min(hi, value + 1)))}
    </div>
  );
}
window.StandingsScreen = StandingsScreen;
